//
//  MLSUserStatus.swift
//  MLSMircoBlog
//
//  Created by 袁航 on 15/8/1.
//  Copyright © 2015年 yuanhang. All rights reserved.
//

import UIKit
import SVProgressHUD
import SDWebImage
class MLSUserStatus: NSObject {
    /// 缓存对应该模型的cell的行高
    var rowHeight: CGFloat?
    /// 微博创建时间
    var created_at: String?
    /// 微博ID
    var id: Int = 0
    /// 微博信息内容
    var text: String?
    /// 微博来源
    var source: String?
    /// 用户
    var user: MLSUserInfo?
    /// 转发数
    var reposts_count: Int = 0
    /// 评论数
    var comments_count: Int = 0
    /// 表态数
    var attitudes_count: Int = 0
    ///  被转发的原微博信息字段，当该微博为转发微博时返回(待用)
    var retweeted_status: MLSUserStatus?
    /// 配图url数组
    var pictURLS: [NSURL]? {
        return retweeted_status == nil ? tempSaveURLs : retweeted_status?.tempSaveURLs
    }
    /// 临时存放URL数组,为了转发微博功能
    private var tempSaveURLs: [NSURL]?
    /// 配图数组
    var pic_urls: [[String: AnyObject]]? {
        didSet {
            // 如果没有图片数组,直接返回
            if pic_urls == nil {
                return
            }
            // 有图片数组,转URL
            tempSaveURLs = [NSURL]()
            for dict in pic_urls! {
                if let urlStr = dict["thumbnail_pic"] as? String {
                    if let url = NSURL(string: urlStr){
                        tempSaveURLs?.append(url)
                    }
                }
            }
        }
    }

    ///  获取模型数组
    class func loadStatus(since_id: Int, max_id: Int, finshed: (statusList:[MLSUserStatus]?, error: NSError?)->()){
        // 发送网络请求获取数据
        MLSNetworkTool.sharNewworkTools.loadStatus(since_id, max_id: max_id) { (result, error) -> () in
            if error != nil {
                // 错误回调
                finshed(statusList: nil, error: error)
                return
            }
            
            if let dictArray = result!["statuses"] as? [[String: AnyObject]] {
                // 字典转模型
                var statusList = [MLSUserStatus]()
                for dict in dictArray {
                   statusList.append(MLSUserStatus(dict: dict))
                }
                // 完成回调
//                finshed(statusList: statusList, error: nil)
                cacheImage(statusList, finshed: finshed)
            }
        }
    }
    ///  缓存图片
    private class func cacheImage(statusList: [MLSUserStatus] ,finshed: (statusList:[MLSUserStatus]?, error: NSError?)->()) {
        // 调度组
        let group = dispatch_group_create()
        // 缓存数据大小
        var dataLength = 0
        // 遍历数组
        for list in statusList {
            // 判断是否存在图片
            guard let urls = list.pictURLS else {
                continue
            }
            
            // 遍历url缓存图片
            for url in urls {
                // 入组
                dispatch_group_enter(group)
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (cacheImage, __, _, _, _) -> Void in
                    // 把image转换成二进制数据
                    if let image = cacheImage {
                        let data = UIImagePNGRepresentation(image)!
                        // 计算整个data的数据
                        dataLength += data.length
                    }
                    // 出租
                    dispatch_group_leave(group)
                })
            }
        }
        
        dispatch_group_notify(group, dispatch_get_main_queue(), { () -> Void in
            finshed(statusList: statusList, error: nil)
            // 打印调试
            print("缓存图片大小\(dataLength / 1024)KB")
        })
        
    }
    
    ///  字典转模型
    init(dict: [String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
///  防止网络获取的key比模型的key多
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
///  在获取到user的信息的时候,转模型
    override func setValue(value: AnyObject?, forKey key: String) {
        // 如果是设置user的数据就转模型
        if key == "user" {
            if let dictValue = value as? [String: AnyObject] {
                user = MLSUserInfo(dict: dictValue)
            }
            return
        }
        //如果有转发微博
        if key == "retweeted_status" {
            if let retValue = value as? [String: AnyObject]{
                retweeted_status = MLSUserStatus(dict: retValue)
            }
            return
        }
        
        super.setValue(value, forKey: key)
    }
    
}
